package oop.ex3.filemanager;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;


//public class UploadRequestThread implements Runnable{
public class UploadRequestThread extends Thread{

	private static final int SERVER_SOCKET_TIMEOUT = 5 * 1000;

	private ServerSocket _listeningSocket;
	private File _directoryPath;
	private volatile boolean _isListening;
	//a list of active uploads:
	private List<UploadThread> _uploadThreads;
		
	public UploadRequestThread(int port, File directoryPath){
		try {
			_listeningSocket = new ServerSocket(port);
			_listeningSocket.setSoTimeout(SERVER_SOCKET_TIMEOUT);
			_directoryPath = directoryPath;
			_uploadThreads = new ArrayList<UploadThread>();
			_isListening = true;
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		UploadThread newUploadThread;
		while(_isListening){
			try {
				newUploadThread = new UploadThread(_listeningSocket.accept(), _directoryPath);
				newUploadThread.start();
				_uploadThreads.add(newUploadThread);
				//if a socket timeout exception is thrown, the "listening" loop should continue running, listening:
			} catch (SocketTimeoutException e) {
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
	public void stopAcceptingUploadRequests() {
		_isListening = false;	
	}

	
	
	public void checkIfFileIsUploaded(String fileName) {
		for(UploadThread uploadThread : _uploadThreads){
			//if the upload thread hadn't recognized yet the file name which it supposed to
			//upload, then this thread waits, in case it's the file this method got as a parameter: 
			if(uploadThread.getFileNameOfUploadingFile()==null){
				synchronized(uploadThread){
					try {
						uploadThread.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			//if this file is being uploaded, the method waits until completion:
			if(fileName.equals(uploadThread.getFileNameOfUploadingFile())){
				try {
					synchronized(uploadThread){
						uploadThread.join();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

	public void waitForAllUploadsToFinish() {
		for(Thread uploadThread : _uploadThreads){
			try {
				synchronized(uploadThread){
					uploadThread.join();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

	

